<?php
/**
 * oscshop2 B2C电子商务系统
 *
 * ==========================================================================
 * @link      http://www.oscshop.cn/
 * @copyright Copyright (c) 2015-2017 oscshop.cn. 
 * @license   http://www.oscshop.cn/license.html License
 * ==========================================================================
 *
 * @author    李梓钿
 *
 */ 
namespace osc\member\controller;
use osc\common\controller\AdminBase;
use think\Db;
use extend\PHPExcel;
class OrderBackend extends AdminBase{
	
	protected function _initialize(){
		parent::_initialize();
		$this->assign('breadcrumb1','会员');
		$this->assign('breadcrumb2','会员订单');
	}
	
     public function index(){

        $result = Db::query('select DISTINCT pay_subject from osc_order');   
        //var_dump($result);

        $this->assign('subject',$result);
		$this->assign('status',Db::name('order_status')->select());
		$this->assign('list',osc_order()->order_list(input('param.'),20));
		$this->assign('empty','<tr><td colspan="20">没有数据~</td></tr>');
		$this->assign('goods_type',osc_goods()->get_goods_type());

    	return $this->fetch();
	 }

	 function export_ticket()
	{
		$param=input('param.');
		
		$map=null;
		
		

		$query=[];
		
		if(isset($param['order_num'])){
			$map['Order.order_num_alias']=['eq',$param['order_num']];	
			$query['order_num']=urlencode($param['order_num']);
		}
		if(isset($param['username'])){
			$map['Member.username']=['like',"%".$param['user_name']."%"];
			$query['username']=urlencode($param['user_name']);
		}
		if(isset($param['status'])){
			$map['Order.order_status_id']=['eq',$param['status']];	
			$query['status']=urlencode($param['status']);
		}

		if(isset($param['pay_subject'])){
			$map['Order.pay_subject']=['eq',$param['pay_subject']];	
			$query['pay_subject']=urlencode($param['pay_subject']);
		}
		
		if(isset($param['type'])){
			$map['Order.type']=['eq',$param['type']];	
			$query['type']=urlencode($param['type']);
		}
		
		if($uid){
			$map['Member.uid']=['eq',$uid];	
		}
		
		$map['Order.order_id']=['gt',0];
		

		Db::view('Order','*')->field()
		->view('Member','username,reg_type,nickname','Order.uid=Member.uid')
		->view('OrderStatus','order_status_id,name','Order.order_status_id=OrderStatus.order_status_id')
		->where($map)
		->order('Order.order_id desc')->select();

		$excel=new Excel();
        $table_name="osc_rang_order";
        $field=["id"=>"序号","id_name"=>"账号名称","trade_id"=>"交易主账号","username"=>"电话号码","exchange_variety_id"=>"交易品种","variety_id"=>"交易品种编号","delivery_num"=>"划拨数量","buy_state"=>"划拨价格","buy_state"=>"划拨日期"];
        

        $dt = date("Y-m-d",time());
        $ft = "配票导出".$dt;
        $excel->setExcelName($ft)
        ->createSheet("待处理",$table_name,$field,$map)
        ->downloadExcel();
	}


	 public function excport()
	 {
	 	$data = input('param.');

	 	if(isset($param['order_num'])){
			$map['Order.order_num_alias']=['eq',$param['order_num']];	
			$query['order_num']=urlencode($param['order_num']);
		}
		if(isset($param['username'])){
			$map['Member.username']=['like',"%".$param['username']."%"];
			$query['username']=urlencode($param['username']);
		}


		$sql = 'select od.order_num_alias, od.pay_subject,od.total,ad.province_name,ad.city_name,ad.country_name,ad.name,ad.telephone from osc_order od,
(select a2.*,b2.area_name province_name from (select a1.*,b1.area_name country_name from (select od.address_id,od.address,od.`name`,od.telephone,od.city_id,od.country_id,od.province_id,oa.area_name city_name 
from osc_area oa, osc_address od  where oa.area_id = od.city_id) a1 ,osc_area b1 where a1.country_id = b1.area_id) a2, osc_area b2 where a2.province_id = b2.area_id) ad where od.address_id = ad.address_id';
		

		if(isset($param['status'])){
			$sql = $sql.' and od.order_status_id = '.$param['status'];
		}

		if(isset($param['pay_subject'])){
			$sql = $sql.' and od.pay_subject = '.$param['pay_subject'];
		}

		$result = Db::query($sql); 
	

	 }

	function exportExcel($title=array(), $data=array(), $fileName='', $savePath='./', $isDown=false)
	{  

	    $obj = new PHPExcel();  
	  
	    //横向单元格标识  
	    $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');  
	      
	    $obj->getActiveSheet(0)->setTitle('sheet名称');   //设置sheet名称  
	    $_row = 1;   //设置纵向单元格标识  
	    if($title){  
	        $_cnt = count($title);  
	        $obj->getActiveSheet(0)->mergeCells('A'.$_row.':'.$cellName[$_cnt-1].$_row);   //合并单元格  
	        $obj->setActiveSheetIndex(0)->setCellValue('A'.$_row, '数据导出：'.date('Y-m-d H:i:s'));  //设置合并后的单元格内容  
	        $_row++;  
	        $i = 0;  
	        foreach($title AS $v){   //设置列标题  
	            $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);  
	            $i++;  
	        }  
	        $_row++;  
	    }  
	  
	    //填写数据  
	    if($data){  
	        $i = 0;  
	        foreach($data AS $_v){  
	            $j = 0;  
	            foreach($_v AS $_cell){  
	                $obj->getActiveSheet(0)->setCellValue($cellName[$j] . ($i+$_row), $_cell);  
	                $j++;  
	            }  
	            $i++;  
	        }  
	    }  
	      
	    //文件名处理  
	    if(!$fileName){  
	        $fileName = uniqid(time(),true);  
	    }  
	  
	    $objWrite = PHPExcel_IOFactory::createWriter($obj, 'Excel2007');  
	  
	    if($isDown){   //网页下载  
	        header('pragma:public');  
	        header("Content-Disposition:attachment;filename=$fileName.xls");  
	        $objWrite->save('php://output');exit;  
	    }  
	  
	    $_fileName = iconv("utf-8", "gb2312", $fileName);   //转码  
	    $_savePath = $savePath.$_fileName.'.xlsx';  
	     $objWrite->save($_savePath);  
	  
	     return $savePath.$fileName.'.xlsx';  
	} 
	 
 	public function show_order(){
    
		$this->assign('data',osc_order()->order_info(input('param.id')));		
		$this->assign('crumbs','订单详情');
				
    	return $this->fetch('show');
	 }
	function print_order(){	 	
		$this->assign('order',osc_order()->order_info(input('param.id')));		
		return $this->fetch('order');	
	 }
	
	function del(){	
		osc_order()->del_order((int)input('param.id'));		
		storage_user_action(UID,admin('username'),config('BACKEND_USER'),'删除了订单');	
		$this->redirect('OrderBackend/index');
	}	
	
	function history(){
		
	 		$model=osc_order();
						
			if(request()->isPost()){				
				
				$post=input('param.');
				if($post['order_status_id']==config('cancel_order_status_id')){
				
					$model->cancel_order($post['id']);		
					storage_user_action(UID,admin('username'),config('BACKEND_USER'),'取消了订单');			
					
					$result=true;
				}else{
					$result=$model->add_order_history($post['id'],$post);
				}
					
				if(!empty($post['transport_c_name'])&&!empty($post['transport_num'])){
					Db::name('order')->where('order_id',$post['id'])->update(array('transport_c_name'=>$post['transport_c_name'],'transport_num'=>trim($post['transport_num'])));
				}	
					
				/**	
				 * 判断是否选择了通知会员，并发送邮件
				 */
				if($post['notify']==1){
					
				}
				
				if($result){
					$this->success='新增成功！！';
				}else{
					$this->error='新增失败！！';
				}
			}
			
			$results = $model->get_order_histories(input('param.id'));
		
			foreach ($results as $result) {
				$histories[] = array(
					'notify'     => $result['notify'] ? '是' : '否',
					'status'     => $result['name'],
					'comment'    => nl2br($result['comment']),
					'date_added' => date('Y/m/d H:i:s', $result['date_added'])
				);
			}	
			
			$this->histories=$histories;

			$this->assign('histories',$histories);	
			
			exit($this->fetch());
	}
	
	function update_order(){
		$data=input('post.');		
		$type=input('param.type');
		
		//更新 order_goods
		$og=Db::name('order_goods')->find($data['order_goods_id']);
		
		if(isset($data['shipping'])){
			$shipping=$data['shipping'];
		}else{
			$shipping=0;
		}
		
		if($type=='quantity'){
					
			$update['quantity']=$data['quantity'];
			$update['total']=$data['quantity']*$og['price'];
			$update['order_goods_id']=$data['order_goods_id'];
			
		}elseif($type=='price'){
			
			$update['price']=$data['price'];
			$update['total']=$og['quantity']*$data['price'];						
			$update['order_goods_id']=$data['order_goods_id'];
			
		}		
		
		if(Db::name('order_goods')->update($update,false,true)){
			
			$total=0;				
			//更新 order
			$order_goods=Db::name('order_goods')->where(array('order_id'=>$data['order_id']))->select();
			
			foreach ($order_goods as $k => $v) {
				$total+=$v['total'];
			}
			
			Db::name('order')->where(array('order_id'=>$data['order_id']))->update(array('total'=>$total+$shipping));
			
			//更新 order_total
			Db::name('order_total')->where(array('order_id'=>$data['order_id']))->delete();
			
			$data['totals'][0]=array(
				'code'=>'sub_total',
				'order_id'=>$data['order_id'],
				'title'=>'商品价格',
				'text'=>'￥'.$total,
				'value'=>$total				
			);
			$data['totals'][1]=array(
				'code'=>'shipping',
				'order_id'=>$data['order_id'],
				'title'=>'运费',
				'text'=>'￥'.$shipping,
				'value'=>$shipping				
			);				
			$data['totals'][2]=array(
				'code'=>'total',
				'order_id'=>$data['order_id'],
				'title'=>'总价',
				'text'=>'￥'.($total+$shipping),
				'value'=>($total+$shipping)				
			);
						
			foreach ($data['totals'] as $k => $v) {
				Db::name('order_total')->insert($v);
			}
			storage_user_action(UID,admin('username'),config('BACKEND_USER'),'更新了订单');	
			
			return true;
			
		}
	}	
	//更新运费
	function update_shipping(){
		
		$d=input('post.');
		
		$shipping=$d['shipping'];
		
		$order_total=Db::name('order_total')->where(array('order_id'=>$d['order_id']))->select();
			
		foreach ($order_total as $k => $v) {
			$total[$v['code']]=$v;
		}
		
		if($total['shipping']['value']!=$shipping){
			
			Db::name('order_total')->where(array('order_id'=>$d['order_id']))->delete();
			
			Db::name('order')->where(array('order_id'=>$d['order_id']))->update(array('total'=>$total['sub_total']['value']+$shipping));
			
			$data['totals'][0]=array(
				'code'=>'sub_total',
				'order_id'=>$d['order_id'],
				'title'=>'商品价格',
				'text'=>'￥'.$total['sub_total']['value'],
				'value'=>$total['sub_total']['value']				
			);
			$data['totals'][1]=array(
				'code'=>'shipping',
				'order_id'=>$d['order_id'],
				'title'=>'运费',
				'text'=>'￥'.$shipping,
				'value'=>$shipping				
			);				
			$data['totals'][2]=array(
				'code'=>'total',
				'order_id'=>$d['order_id'],
				'title'=>'总价',
				'text'=>'￥'.($total['sub_total']['value']+$shipping),
				'value'=>($total['sub_total']['value']+$shipping)				
			);
			
			foreach ($data['totals'] as $k => $v) {
				Db::name('order_total')->insert($v);
			}
			storage_user_action(UID,admin('username'),config('BACKEND_USER'),'更新了订单运费');
			return true;
		}
		
	
		
	}
}
?>